JAVA筆記_ 檔案處理


檔案讀取與寫入

在處理檔案時必須先匯入 import java.io.*;
並且需要IOException例外處理

創建檔案

File f = new File("file's path"); f為抓取路徑上檔案文件的File物件
createNewFile() true表示成功 false表示檔案已經存在

import java.io.*;
public class createfile{
    public static void main(String arg[]){\
        try{
            File f= new File("file's path");
            if(f.createNewFile()) System.out.println("File create:"+f.getName());
            else  System.out.println("File already exists.");
        }
        catch(IOException e) e.printStackTrace();
    }
}

寫入檔案

開啟寫入串流,再將串流內容寫進檔案文件之中,以FileWriter物件操作
FileWriter myWriter = new FileWriter("filename.txt");
之後Filewriter物件以write()方法即可寫入
myWriter.write("Files in Java might be tricky, but it is fun enough!");
使用完之後要將寫入串流物件關閉
myWriter.close();

-- close可以釋放資源且必須存在,通常放再try/catch/finally的finally區塊中,表示無論執行結果為何都要將串流資源關閉

讀取檔案

開啟引入串流,將檔案文件內容引入到串流中,以Scanner物件操作import java.util.Scanner;

 File myObj = new File("filename.txt");
 Scanner myReader = new Scanner(myObj);

Scanner物件成功引入檔案文件後, 再以一行行的方式讀取

while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }

最終將引入串流關閉
myReader.close();

刪除檔案

對File物件使用delete()方法來刪除
true表示刪除且刪除成功
false表示刪除失敗

File myObj = new File("filename.txt"); 
if (myObj.delete()) System.out.println("Deleted the file: " + myObj.getName());
else System.out.println("Failed to delete the file.");

綜合使用code

我們折磨自己,先創立檔案,寫入讀取,之後把它刪除

import java.io.*;
import java.util.Scanner;

public class Filepractice {
    public static void main(String args[]) throws IOException{
        //create
        File f =new File("file.txt"); 
        if(f.createNewFile()){
            //write
            FileWriter fw =new FileWriter("file.txt");
            fw.write("If you want to study in NCCU,\nyou should make your English better!");
            fw.close();

            //read
            Scanner fr=new Scanner(f);
            while(fr.hasNextLine()){
                String data=fr.nextLine();
                System.out.println(data);
            }
            fr.close();

            //delete
            if(f.delete()) System.out.println("file delete");
            else System.out.println("file not delete yet");
        }
        else System.out.println();
    }
}






你可能感興趣的文章

再戰 todo list 與其他 hooks

再戰 todo list 與其他 hooks

Angular 專案使用 Font Awesome Free Icon

Angular 專案使用 Font Awesome Free Icon

Vue3 安裝 SCSS 編譯器!然後跑不起來怎麼辦?

Vue3 安裝 SCSS 編譯器!然後跑不起來怎麼辦?






留言討論